package com.icw.decoupling.impl.tool;

import java.io.Writer;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.templateresolver.StringTemplateResolver;

import com.icw.decoupling.defi.proxy.GenericSrvProxy;
import com.icw.decoupling.defi.tool.DataExchange;
import com.icw.decoupling.defi.tool.ResourceContextProcessor;
import com.icw.decoupling.defi.tool.TemplateManager;
import com.icw.resource.inner.entity.IcwTemplate;
import com.icw.utility.IcwUtils;
import com.icw.utility.PoEntityHelper;

@Component
public class DefaultTemplateManager implements TemplateManager {

	@Autowired
	GenericSrvProxy srv;

	@Autowired
	DataExchange de;

	@Autowired
	ResourceContextProcessor rcp;

	private final TemplateEngine templateEngine;

	public DefaultTemplateManager() {
		templateEngine = new TemplateEngine();
		templateEngine.setTemplateResolver(new StringTemplateResolver());
	}

	@Override
	public void print(String templateId, Object contextObj, Writer writer) throws Exception {
		try {
			IcwTemplate template = srv.one(IcwTemplate.class, templateId);
			if ("01".equals(template.getType())) {
				@SuppressWarnings("unchecked")
				Map<String, Object> context = Map.class.isInstance(contextObj) ? (Map<String, Object>) contextObj : de.parseMap(contextObj);
				Object[] actions = de.parse(template.getVariables(), Object[].class);
				rcp.process(actions, context);
				templateEngine.process((String) PoEntityHelper.readValueByProperty(template, "content"), new Context(null, context), writer);
			}
		} finally {
			IcwUtils.closeClosable(writer);
		}
	}
}
